<template>
  <uni-nav-bar title="新增任务" left-icon="left" @clickLeft="navBack" :fixed="true" statusBar></uni-nav-bar>
  <view :style="{ opacity: curPage === 'map' ? '0' : '1'}">
    <view class="package_sale" style="text-align: center;" @click="navTo('administrator/dispatch/searchFriend')">搜索车友
    </view>
    <view class="package_sale">
      <view class="space-between">
        <view>车友</view>
        <input class="uni-input" maxlength="10" placeholder="请输入车友姓名" style="text-align: right;"
          v-model="driver_name" />
      </view>
      <view class="space-between top">
        <view>手机号</view>
        <input class="uni-input" maxlength="11" placeholder="请输入手机号" v-model="driver_mobile" />
      </view>
      <view class="space-between top">
        <view>车牌号</view>
        <view :style="{color:numberplate==='请输入车牌号'?'#808080':''}" @click="openPlatePicker()">{{numberplate}}</view>
      </view>
      <view class="space-between top">
        <view>配送地址</view>
        <view @click="chooseLocation" class="center"
          style="align-items: flex-start;width:70%;justify-content: flex-end;">{{locName}} <uni-icons type="location"
            size="25"></uni-icons>
        </view>
      </view>
      <!-- <view class="top">
        <view>配送方式</view>
        <view class="center lis" v-if="listAll&&listAll.time">
          <view v-for="(item,index) in listAll.time" :key="index" :class="time===item.value?'active':''"
            @click="()=>time=item.value">{{item.label}}
          </view>
        </view>
      </view> -->
      <view class="space-between top">
        <view>调度时间</view>
        <view class="center" style="justify-content: flex-end;">
          <view style="font-size: 28rpx;"> {{delivery_time?'指定时间':'预约时间'}}</view>
          <view style="font-size: 24rpx;margin-left:10rpx;" @click="openTimePicker()">
            大约{{time}}送达 ></view>
        </view>
      </view>
      <view class="top">
        <view>配送员</view>
        <view class="center lis" v-if="listAll&&listAll.staff">
          <view v-for="(item,index) in listAll.staff" :key="index" :class="staff_id===item.value?'active':''"
            @click="()=>staff_id=item.value">
            {{item.label}}
          </view>
        </view>
      </view>
      <view class="top">
        <view>备注</view>
        <textarea class="textarea" v-model="value" placeholder="备注"></textarea>
      </view>
    </view>
    <view class="add" @click="submit()">确定</view>
    <!-- 车牌弹框 -->
    <VehiclePlatePad v-if="isShowPlatePad" @cancel="isShowPlatePad = false" @confirm="confirmPlate" />
  </view>
  <!-- 预约时间弹框 -->
  <TimePicker ref="TimePickerRef" @jisuanScore="jisuanScores" />
  <!-- 选择地址列表 -->
  <view v-if="curPage === 'map'"><web-view :src="mapURI"></web-view></view>
  <!-- 当前位置经纬度 -->
  <Lotlats @position="position"></Lotlats>
</template>

<script setup lang="ts">
  import { navBack, navTo } from '@/utils/navigator';
  import VehiclePlatePad from '@c/common/VehiclePlatePads.vue';
  import Lotlats from '@c/team/Lotlat.vue';
  import { onShow, onUnload } from '@dcloudio/uni-app';
  import { toPublish } from '@mqtt';
  import { getTaskParams } from '@/gql/dispatch';
  import { showLoading, errorToast, successToast } from '@/utils/prompt';
  import TimePicker from '@c/reservation/TimePicker.vue';
  import { ref, Ref } from 'vue';
  import { getDriverID } from '@/stores/driverID';
  const admin_id = getDriverID();//用户ID
  const isShowPlatePad = ref(false); //添加车牌弹框
  const numberplate = ref('请输入车牌号'); //车牌号
  const value = ref('');//备注
  const TimePickerRef = ref(null);//预约时间弹框
  const delivery_time = ref() //时间戳
  const time = ref()//具体时间
  const staff_id = ref() //选择地推人员ID
  const driver_name = ref('') //车友姓名
  const driver_mobile = ref('') //车友是手机号码
  const riders = ref() //存储车友信息
  const listAll = ref() //配送员列表
  // 地图/地址
  const curPage : Ref<'form' | 'map'> = ref('form');
  const longitude = ref()
  const latitude = ref()
  const mapURI = ref('');
  const locName = ref('')
  onUnload(() => {
    uni.removeStorageSync('riders');
  })
  onShow(() => {
    riders.value = uni.getStorageSync('riders');
    driver_name.value = riders.value.name
    driver_mobile.value = riders.value.mobile
    numberplate.value = riders.value.cart_code ? riders.value.cart_code : '请输入车牌号'
  })
  // 获取数据信息
  init()
  function init() {
    showLoading()
    const payload = {
      query: getTaskParams
    };
    toPublish(
      'ql/control/getTaskParams',
      payload,
      (obj : any) => {
        uni.hideLoading();
        const { getTaskParams } = obj.data;
        listAll.value = getTaskParams
        // time.value = getTaskParams.time[0].value
        staff_id.value = getTaskParams.staff[0].value
        TimePickerRef.value.init()
      }
    );
  }
  function confirmPlate(plate : string) {
    numberplate.value = plate;
    isShowPlatePad.value = false;
  }
  // 打开车牌弹框
  function openPlatePicker() {
    isShowPlatePad.value = true
  }
  // TimePicker
  function openTimePicker() {
    TimePickerRef.value.open();
  }
  function position(lat : number, lot : number) {
    longitude.value = lot;
    latitude.value = lat;
  }
  // 跳转到地址列表 选择位置信息
  function chooseLocation() {
    mapURI.value = `https://apis.map.qq.com/tools/locpicker?coord=${latitude.value},${longitude.value}&search=1&type=1&key=URFBZ-F4TKI-SLPGX-57GMO-ZHYM6-BCFSL&referer=安蓝环保`;
    curPage.value = 'map';
    function msgListener(event : any) {
      // 接收位置信息，用户选择确认位置点后选点组件会触发该事件，回传用户的位置信息
      var loc = event.data;
      if (loc && loc.module == 'locationPicker') {
        console.log(JSON.stringify(loc) + '*****')
        curPage.value = 'form';
        longitude.value = loc.latlng.lng;
        latitude.value = loc.latlng.lat;
        locName.value = loc.poiname
        //防止其他应用也会向该页面post信息，需判断module是否为'locationPicker'
        window.removeEventListener('message', msgListener);
      }
    }
    window.addEventListener('message', msgListener, false);
  }
  // 预约时间
  function jisuanScores(tim : any, date : string, day : string) {
    delivery_time.value = tim
    time.value = day ? day + '-' + date : date
  }
  //提交分配任务
  function submit() {
    if (!locName.value) {
      errorToast('请选择位置信息')
      return
    }
    if (!driver_name.value) {
      errorToast('请输入车友姓名')
      return
    }
    showLoading()
    const payload = {
      driver_id: riders.value.id ? riders.value.id : 0,
      admin_id,
      driver_name: driver_name.value,
      driver_mobile: driver_mobile.value,
      cart_code: numberplate.value === '请输入车牌号' ? '' : numberplate.value,
      des: value.value,
      staff_id: staff_id.value,
      longitude: longitude.value,
      latitude: latitude.value,
      delivery_address: locName.value,
      delivery_time: delivery_time.value,
    };
    toPublish('control/addTask',
      payload,
      (obj : any) => {
        uni.hideLoading();
        const { code, msg } = obj;
        if (code === 1) {
          successToast(msg)
          navBack()
        } else {
          errorToast(msg)
        }
      }
    );
  }
</script>

<style scoped lang="less">
  .top {
    margin-top: 20rpx;
    align-items: flex-start;

    input {
      text-align: right;
    }
  }

  .lis {
    flex-wrap: wrap;

    view {
      min-width: 160rpx;
      text-align: center;
      padding: 13rpx 20rpx 15rpx;
      box-sizing: border-box;
      background-color: #ECF1F5;
      color: #333;
      border-radius: 5px;
      margin: 18rpx 20rpx 10rpx 0px;
    }

    .active {
      background: #3F90FF;
      color: #FFFFFF;
    }
  }

  .add {
    width: 480rpx;
    height: 100rpx;
    background: linear-gradient(-10deg, #2C96F9, #1B91FF);
    border-radius: 5px;
    text-align: center;
    line-height: 100rpx;
    color: #fff;
    margin: 50rpx auto 0px;
    font-size: 32rpx;
  }

  uni-textarea {
    width: 100%;
    background: #eee;
    border-radius: 5px;
    margin-top: 20rpx;
    padding: 15rpx;
    box-sizing: border-box;
  }
</style>